package com.glr.subject.service;

import com.glr.common.utils.JsonUtils;
import com.glr.common.utils.RedisOperator;
import com.glr.subject.dao.CatalogDao;
import com.glr.subject.entity.Catalog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 学科目录业务层
 *
 * @author GLoRy
 * @date 2021/6/8 22:14
 */
@Service
public class CatalogService {

    @Autowired
    private CatalogDao catalogDao;

    @Autowired
    private RedisOperator redisOperator;

    /**
     * 增加学科目录
     *
     * @param catalog 学科目录实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void save(Catalog catalog) {
        catalogDao.save(catalog);
    }

    /**
     * 修改学科目录
     *
     * @param catalog 学科目录实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(Catalog catalog) {
        catalogDao.save(catalog);
    }

    /**
     * 删除学科目录
     *
     * @param id 学科目录id
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(Integer id) {
        catalogDao.deleteById(id);
    }

    /**
     * 根据id查询学科目录
     *
     * @param id 学科目录id
     * @return 学科目录信息
     */
    public Catalog findById(Integer id) {
        return catalogDao.findById(id).orElse(null);
    }

    /**
     * 查询学科目录
     *
     * @return 学科目录信息
     */
    public List<Catalog> findAll() {
        List<Catalog> catalogs = catalogDao.findAll();
        String value = JsonUtils.objectToJson(catalogs);
        redisOperator.set("catalogList", value);
        return catalogs;
    }

    /**
     * 分页查询学科目录
     *
     * @param page     当前页
     * @param pageSize 每页行数
     * @return 学科目录分页信息
     */
    public Page<Catalog> findByPage(Integer page, Integer pageSize) {
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);
        Page<Catalog> catalogs = catalogDao.findAll(pageRequest);
        String value = JsonUtils.objectToJson(catalogs);
        redisOperator.set("catalogPage", value);
        return catalogs;
    }
}
